package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;

import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.math3.stat.descriptive.summary.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import static com.zzyl.common.core.domain.AjaxResult.success;


/**
 * 设备Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-05
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private IoTDAClient ioTDAClient;


    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteById(id);
    }

    @Override
    public void syncProductList() {
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置条数
        listProductsRequest.setLimit(50);
        //发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if(response.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        //存储到redis
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr(response.getProducts()));

    }

   /* @Override
    public List<ProductVo> allProduct() {
       List<ProductVo>  products = redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        return List.of();
    }*/
    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //从redis中查询数据
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        //如果数据为空，则返回一个空集合
        if(StringUtils.isEmpty(jsonStr)){
            return Collections.emptyList();
        }
        //解析数据，并返回
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //1. 判断设备名称是否重复
        Long count = lambdaQuery()
                .eq(Device::getDeviceName, deviceDto.getDeviceName())
                .count();
        if (count > 0) {
            throw new BaseException("设备名称重复");
        }
        //2. 判断设备标识是否重复
        count = lambdaQuery()
                .eq(Device::getNodeId, deviceDto.getNodeId())
                .count();
        if (count > 0) {
            throw new BaseException("设备标识码重复");
        }
        //判断如果是随身设备，将物理位置设置为-1
        if (deviceDto.getLocationType() == 0) {
            deviceDto.setPhysicalLocationType(-1);
        }


        //3. 判断同一位置是否绑定了相同的产品
        count = lambdaQuery()
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .count();
        if (count > 0) {
            throw new BaseException("同一位置绑定了相同的产品");
        }

        //4. 注册设备到华为iot平台
        //随机生成密钥
        String secret = UUID.randomUUID().toString().replaceAll("-", "");

        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice

                .withDeviceName(deviceDto.getDeviceName())
                .withProductId(deviceDto.getProductKey())
                .withNodeId(deviceDto.getNodeId())
                .withAuthInfo(new AuthInfo()
                        .withSecret(secret));

        addDeviceRequest.withBody(addDevice);
        AddDeviceResponse response = null;
        try {
            response = ioTDAClient.addDevice(addDeviceRequest);
        } catch (Exception e) {
            log.error("注册设备失败", e);
            throw new BaseException("注册设备失败");
        }


        //5.保存设备数据到数据库
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setSecret(secret);
        device.setIotId(response.getDeviceId());
        save(device);
    }

    @Override
    public DeviceDetailVo detail(String iotId) {
        //1. 查询数据库
        Device device = lambdaQuery()
                .eq(Device::getIotId, iotId)
                .one();
        if (ObjectUtil.isNull(device)) {
            throw new BaseException("设备不存在");
        }
        //2. 查询华为云iot平台
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = null;
        try {
            response = ioTDAClient.showDevice(request);
        } catch (Exception e) {
            log.error("查询iot平台出错", e);
            throw new BaseException("查询iot平台出错");
        }



        //3.封装到vo返回
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);

        //获取设备状态
        String status = response.getStatus();
        //获取设备激活时间
        String activeTimeStr = response.getActiveTime();
        if(StrUtil.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            vo.setActiveTime(activeTime);

        }
        vo.setDeviceStatus(status);
        return vo;
    }
    /**
     * 修改设备
     *
     * @param dto 设备
     * @return 结果
     */
    @Override
    public int updateDevice(DeviceDto dto)
    {
        //修改iot平台的数据
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        //条件，设备id
        request.withDeviceId(dto.getIotId());
        UpdateDevice body = new UpdateDevice();
        //设备名称
        body.withDeviceName(dto.getDeviceName());
        request.withBody(body);
        UpdateDeviceResponse response;
        try {
            response = ioTDAClient.updateDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 修改设备，调用失败");
        }

        //修改本地数据
        Device device = BeanUtil.toBean(dto, Device.class);
        try {
            return updateById(device)?1:0;
        } catch (Exception e) {
            throw new BaseException("相同的位置不能绑定同一个产品");
        }
    }

    /**
     * 批量删除设备
     *
     * @param iotId 需要删除的设备主键
     * @return 结果
     */


    @Override
    public AjaxResult queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询设备上报数据，调用失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if(CollUtil.isEmpty(shadow)){
            List<Object> emptyList = Collections.emptyList();
            return success(emptyList);
        }
        //返回数据
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());

        List<Map<String,Object>> list = new ArrayList<>();

        //处理上报时间日期
        LocalDateTime activeTime =  LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        jsonObject.forEach((k,v)->{
            Map<String,Object> map = new HashMap<>();
            map.put("functionId",k);
            map.put("value",v);
            map.put("eventTime",eventTime);
            list.add(map);
        });

        return success(list);
    }

    /**
     * 删除设备信息
     *
     * @param iotId 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(String iotId)
    {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        try {
            ioTDAClient.deleteDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 删除设备，调用失败");
        }

        return remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId))?1:0;
    }



}
